﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using BakalarskaPraca.Generation.Data;
using BakalarskaPraca.Generation.Tasks;
using ColladaDotNet;
using ColladaDotNet.Geometry;

namespace BakalarskaPraca.Forms.Controls
{
    public partial class ProjectLoader : UserControl
    {
        //public delegate void AfterLoading(ProjectData data);

        private Action<ProjectData> _callack;
        public ProjectLoader()
        {
            InitializeComponent();
        }

        public void CancelOperation()
        {
            this.ProjectLoadingWorker.CancelAsync();
            this.ChangeLabelText("Cancelling...");
        }

        public void ChangeLabelText(string text)
        {
            this.Invoke((MethodInvoker)delegate
                                           {
                                               this.MainLabel.Text = text;
                                           });
        }

        public void StartLoading(ProjectData data, Action<ProjectData> callback)
        {
            this._callack = callback;
            this.ProjectLoadingWorker.RunWorkerAsync(data);
        }

        private void ProjectLoadingWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            ProjectData data = e.Argument as ProjectData;
            if (data == null)
            {
                MessageBox.Show("Project file was corrupted");
                e.Cancel = true;
                return;
            }
            this.ChangeLabelText("Loading model...");
            data.ColladaDocument = new ColladaDocument(data.ModelFileName, data.XmlDocument);
            GeometryLoader geometryLoader = new GeometryLoader(ChangeLabelText, "Loading geometries... ");
            Dictionary<string, Geometry> d = geometryLoader.LoadGeometries(data.ColladaDocument);
            SceneLoader sceneLoader = new SceneLoader(ChangeLabelText, "Loading scene... ");
            data.Scene = new ModelScene(sceneLoader.LoadScene(data.ColladaDocument.VisualScenes[0], d));
            this.ChangeLabelText("Importing scene...");
            data.Polygons = new List<Polygon>();
            data.Scene.Geometries.ForEach(g => g.Polygons.ForEach(data.Polygons.Add));
            e.Result = data;
        }

        private void ProjectLoadingWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                ProjectData data = e.Result as ProjectData;
                if (data != null)
                {
                    this._callack(data);
                }
            }
            this.Hide();
        }
    }
}
